package com.qiu.firechill.common.sql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * @Authhor: qiu
 * @Date: 2020/10/25 8:38 下午
 * @Des: 占位符工具类
 */

public class SqlPlaceholder {

    /**
     * 单参数的sql占位符插入
     * @param connect
     * @param sql
     * @param param
     * @return
     */
   public static PreparedStatement setOneParam(Connection connect, String sql, Object param){
       PreparedStatement pstmt = null;
       try {
           pstmt = connect.prepareStatement(sql);
           if(param instanceof String){
               pstmt.setString(1, (String)param);
           }else if(param instanceof  Integer){
               pstmt.setInt(1, (Integer) param);
           }
       } catch (SQLException throwables) {
           throwables.printStackTrace();
       }
       return pstmt;
   }

    /**
     * 多参数的占位符插入,而且有index的前提下 代理专用
     * @param connect
     * @param sql
     * @param params
     * @param args
     * @return
     */
   public static PreparedStatement setParamHasIndexAndValue(Connection connect,String sql,String[] params,Object[] args){
       PreparedStatement pstmt = null;
       try {
           pstmt = connect.prepareStatement(sql);
           //将使用端的实参得到set进sql的?中
           for (int i = 0; i < params.length; i++) {
               Integer index = Integer.parseInt(params[i]);
               if(args[i] instanceof  String){
                   pstmt.setString(index, (String)args[i]);
               }else if(args[i] instanceof  Integer){
                   pstmt.setInt(index, (Integer) args[i]);
               }
           }
       } catch (SQLException throwables) {
           throwables.printStackTrace();
       }
       return pstmt;
   }

    /**
     * 多参数的占位符插入,仅有值的情况下
     * @param connect
     * @param sql
     * @param vals
     * @return
     */
   public static PreparedStatement setParamHasValue(Connection connect, String sql, List<Object> vals) {
       PreparedStatement pstmt = null;
       try {
           pstmt = connect.prepareStatement(sql);
           //jdbc的sql占位符是从1开始的
           for (int i = 0; i < vals.size(); i++) {
               Object real = vals.get(i);
               if (real instanceof String) {
                   pstmt.setString(i + 1, (String) real);
               } else if (real instanceof Integer) {
                   pstmt.setInt(i + 1, (Integer) real);
               } else if (real == null) {
                   pstmt.setObject(i + 1, null);
               }
           }
       } catch (SQLException throwables) {
           throwables.printStackTrace();
       }
       return pstmt;
   }
}
